package com.lsc.jdbc.demo.jdbc.util;

import java.io.IOException;
import java.sql.*;
import java.util.Properties;

public class JdbcUtils {

    static private String driver;
    static private String url;
    static private String username;
    static private String password;
    static Connection connection;

    static {
        /* 1. 使用 Properties 配置类对象 来 读取 数据 */
        Properties properties = new Properties();
        try {
//            properties.load(new FileInputStream("src/com/lsc/jdbc/demo/util/mysqlConnectInfo.ini"));
            properties.load(JdbcUtils.class.getClassLoader().getResourceAsStream("mysqlConnectInfo.ini"));
        } catch (IOException e) {
            e.printStackTrace();
        }

        driver = properties.getProperty("Driver");
        url = properties.getProperty("url");
        username = properties.getProperty("username");
        password = properties.getProperty("password");

        /* 注册驱动 */
        try {
            Class.forName(driver);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

    }

    public static Connection getCon() {

        try {
            connection = DriverManager.getConnection(url, username, password);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return connection;
    }

    public static void release(Connection connection, Statement statement, ResultSet resultSet, PreparedStatement preparedStatement) {

        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }

        }
        if (statement != null) {
            try {
                statement.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }

        }
        if (resultSet != null) {
            try {
                resultSet.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }

        }

        if (preparedStatement != null) {
            try {
                preparedStatement.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }

        }

    }


}
